package net.bingosoft.common.service;

import java.lang.reflect.Method;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import bingo.persister.Persister;

/**
 * 2008-4-21 下午05:47:25
 * Author:yangdongyu(yangdy@bingosoft.net)
 * ReadMe:服务类的事务代理拦截器
 * ChangeLog:
 */
public class ServiceTransactionInterceptor implements MethodInterceptor {
	private static final Log log = LogFactory.getLog(ServiceTransactionInterceptor.class);


	/* (non-Javadoc)
	 * @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
	 */
	public Object invoke(MethodInvocation mi) throws Throwable {
		Object object = mi.getThis();
		Method method = mi.getMethod();
		Object result = null;
		Persister p;
		boolean useTransaction = method.isAnnotationPresent(Transaction.class);
		if(!useTransaction || "getPersister".equals(method.getName())){
			return mi.proceed();
		}
		if(!(object instanceof IPersisterAware)){
			throw new RuntimeException("被代理的目标类必须实现接口net.bingosoft.common.service.IPersisterAware,请检查...");
		}else{
			p = ((IPersisterAware)object).getPersister();
		}
			
		String methodName = method.getName();
		if(useTransaction){
			try {
				log.debug("开启事务...");
				p.beginTransaction();
				result = mi.proceed();
				p.commit();
				log.debug("提交事务...");
			} catch (Throwable ex) {
				p.rollback();
				log.error("调用方法: " + methodName + " 发生[" + ex.getMessage() + "]异常,事务回滚...",ex);
				throw ex;
			}
		}
		return result;
	}

}
